﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using MoiGioiHDBank.DAO;
using MoiGioiHDBank.DTO;

namespace MoiGioiHDBank
{
    public class MineUtils
    {
        public static string szSecureKey = "12345678";

        public static DESCryptoServiceProvider DESalg = new DESCryptoServiceProvider();

        public static string ByteArrayToString(byte[] bytes)
        {
            StringBuilder hex = new StringBuilder(bytes.Length * 2);
            foreach (byte b in bytes)
            {
                hex.AppendFormat("{0:x2}", b);
            }
            return hex.ToString();
        }

        public static byte[] StringToByteArray(String hexString)
        {
            int numberChars = hexString.Length;
            byte[] bytes = new byte[numberChars / 2];
            for (int i = 0; i < numberChars; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
            }
            return bytes;
        }

        public static string SIDGenerate()
        {
            DateTime currentDate = DateTime.Now;
            byte[] encryptedByteArray = MaHoa(currentDate.ToString());
            string SID = ByteArrayToString(encryptedByteArray);
            return SID;
        }

        public static byte[] MaHoa(string Data)
        {
            try
            {
                DESalg.Key = ASCIIEncoding.ASCII.GetBytes(szSecureKey);
                DESalg.IV = ASCIIEncoding.ASCII.GetBytes(szSecureKey);
                MemoryStream mStream = new MemoryStream();

                CryptoStream cStream = new CryptoStream(mStream,
                    new DESCryptoServiceProvider().CreateEncryptor(DESalg.Key, DESalg.IV),
                    CryptoStreamMode.Write);

                byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);

                cStream.Write(toEncrypt, 0, toEncrypt.Length);
                cStream.FlushFinalBlock();

                byte[] ret = mStream.ToArray();

                cStream.Close();
                mStream.Close();

                return ret;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("Loi roi: {0}", e.Message);
                return null;
            }

        }

        public static string GiaiMa(byte[] Data)
        {
            try
            {
                DESalg.Key = ASCIIEncoding.ASCII.GetBytes(szSecureKey);
                DESalg.IV = ASCIIEncoding.ASCII.GetBytes(szSecureKey);

                MemoryStream msDecrypt = new MemoryStream(Data);

                CryptoStream csDecrypt = new CryptoStream(msDecrypt,
                    new DESCryptoServiceProvider().CreateDecryptor(DESalg.Key, DESalg.IV),
                    CryptoStreamMode.Read);

                byte[] fromEncrypt = new byte[Data.Length];

                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
                string ketqua =  new ASCIIEncoding().GetString(fromEncrypt);
                return ketqua.Substring(0, ketqua.IndexOf('\0'));
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("Loi roi: {0}", e.Message);
                return null;
            }
        }

        public static bool KiemTraTimeOut(string SID)
        {
            bool kq = false;
            byte[] btimout = MineUtils.StringToByteArray(SID);
            string stimeout = MineUtils.GiaiMa(btimout);
            DateTime dtime = DateTime.Parse(stimeout);
            TimeSpan ts = DateTime.Now - dtime;
            if (ts.TotalSeconds < (int)ThamSo.TimeOut)
            {
                kq = true; // con timeout
            }
            else // het timeout nhg co trong csdl
            {
                SIDDAO.XoaSID(SID);
            }
            return kq;
        }

        public static bool KiemTraTienGui(int soTienGui)
        {
            if (soTienGui % 1000 == 0)
                return true;
            return false;
        }

        public static int SIDChecker(string SIDString)
        {
            int kq = -100;// sai sid nhap sai
            string SID = SIDDAO.LaySID(SIDString);
            if (SID != "") // co ton tai SID
            {
                if (KiemTraTimeOut(SID) == true)
                {
                    kq = 0;// con time out
                }
                else
                {
                    kq = -99;// het time out
                }
            }
            return kq;
        }
        private static string ChuyenHeHexan(byte[] arr)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < arr.Length; i++)
            {
                sb.Append(arr[i].ToString("x2"));
            }

            return sb.ToString();
        }
        private static string getSHA1Hash(string source)
        {
            SHA1 sh = SHA1.Create();
            byte[] arr = sh.ComputeHash(Encoding.Unicode.GetBytes(source));
            return ChuyenHeHexan(arr);
        }
        public static string HashPass(string userName, string password)
        {
            return getSHA1Hash(password + userName[0] + userName[userName.Length - 1]);
        }


    }
}